package com.zjdiepu.www.manage.api.dh;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.ExcelUtil;
import com.zjdiepu.www.config.FileProperty;
import com.zjdiepu.www.ibiz.dh.IDhDepositMoneyService;
import com.zjdiepu.www.model.dh.dto.DhDepositMoney;
import com.zjdiepu.www.model.dh.ext.DhDepositMoneyExt;
import com.zjdiepu.www.model.dh.vo.DhDepositMoneyVo;

/**
 * Controller层<br/>
 * @author zhangpp<br/>
 * @time 2017年05月16日 15时56分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "DhDepositMoneyController", produces="application/json;charset=UTF-8")
@Api(tags = {""}, produces="application/json;charset=UTF-8")
public class DhDepositMoneyController extends BaseController {
    @Resource
    private IDhDepositMoneyService dhDepositMoneyService;
    
    @Resource
	private FileProperty fileProperty;

    @ApiOperation(value = "下载客户退押金", response = Boolean.class, httpMethod="GET", tags={"下载合同"})
    @RequestMapping(value = "download", method = RequestMethod.GET)
	public ApiResponse download(HttpServletResponse response,String busiId) {  
		List<DhDepositMoneyVo> list=dhDepositMoneyService.downloadExcel(busiId);
		String path="";
		String pathTo="";
		String bocName="";
		bocName=fileProperty.getCustomerPath();
		try {
			HttpSession session = request.getSession();      
			ServletContext  application  = session.getServletContext();  
			String serverRealPath = application.getRealPath("/WEB-INF");
			serverRealPath = serverRealPath.replaceAll("\\\\", "/");
			path = serverRealPath + "/" + fileProperty.getTemplet()+new String(bocName.getBytes("ISO-8859-1"),"UTF-8");
	        pathTo=serverRealPath + "/" + new String(bocName.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if(list ==null || list.size()==0){
			return ApiResponse.fail(100300,ResultFlagType.MISSING.getValue());
		}else{
			ExcelUtil.excelCopy(new File(path), new File(pathTo));
			importExcel(list,pathTo);//往excel写数据
			downloadExcel(pathTo,response,list.get(0).getCustomerName());
		}
		return ApiResponse.success(true);
    }  
    
    private void importExcel(List<DhDepositMoneyVo> list, String pathTo) {
    	InputStream ins = null;
        Workbook wb = null;     
        try {
			ins=new FileInputStream(new File(pathTo));
			wb= new XSSFWorkbook(ins);
			ins.close();     
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
        Sheet sheet=wb.getSheetAt(0);
         //创建sheet对象   
        if (sheet==null) {
            sheet = (Sheet) wb.createSheet("sheet1");  
        }
        XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();
        XSSFCellStyle style1 = (XSSFCellStyle) wb.createCellStyle();
        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    	style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        
    	style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    	style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    	Font font = wb.createFont();
        font.setFontHeightInPoints((short)13); 
        font.setColor(HSSFColor.RED.index);   
        style.setFont(font);
        style1.setFont(font);
        CellRangeAddress cra1 =new CellRangeAddress(4, 4, 5, 7); // 起始行, 终止行, 起始列, 终止列  
        CellRangeAddress cra =new CellRangeAddress(3, 3, 2, 7); 
        sheet.addMergedRegion(cra);  
        sheet.addMergedRegion(cra1);  
        DhDepositMoneyVo dhDepositMoneyVo=list.get(0);
//        String typeRefundDisplay=cachedDictionaryService.getName(dhDepositMoneyVo.getTypeRefund(),DataDicType.MARGINTYPE);
        String yongtu=dhDepositMoneyVo.getCustomerName()+dhDepositMoneyVo.getTypeRefund()+dhDepositMoneyVo.getSgs()+dhDepositMoneyVo.getLicensePlate();
        Row row=sheet.getRow(3);
		row.createCell(2).setCellValue(yongtu);
		row.getCell(2).setCellStyle(style);
		style1.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		row.getCell(2).setCellStyle(style1);
		
		Row row1=sheet.getRow(4);
		row1.createCell(5).setCellValue(dhDepositMoneyVo.getAmountApply()==null?0:dhDepositMoneyVo.getAmountApply());
		row1.getCell(5).setCellStyle(style);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		
		Row row2=sheet.getRow(5);
		row2.createCell(2).setCellValue(dhDepositMoneyVo.getOrgName());
		row2.getCell(2).setCellStyle(style);
		
		Row row3=sheet.getRow(5);
		row3.createCell(5).setCellValue(dhDepositMoneyVo.getModifierName());
		row3.getCell(5).setCellStyle(style);
		
		Row row4=sheet.getRow(7);
		row4.createCell(5).setCellValue(dhDepositMoneyVo.getCustomerName());
		row4.getCell(5).setCellStyle(style);
		//创建文件流   
        OutputStream stream;
		try {
			stream = new FileOutputStream(pathTo);
			wb.setForceFormulaRecalculation(true);
			//写入数据   
			wb.write(stream);  
			//关闭文件流   
			stream.close();  
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}

	private void downloadExcel(String pathTo, HttpServletResponse response,
			String customerName) {
    	try {    
			// path是指欲下载的文件的路径。    
			File file = new File(pathTo);    
			// 取得文件名。    
			String filename = file.getName();   
			if(filename.contains(".")){
				String[] filenames= filename.split("\\.");
				filename="客户"+"-"+customerName+"\\."+filenames[1];
			}
			// 以流的形式下载文件。    
			InputStream fis = new BufferedInputStream(new FileInputStream(pathTo));    
			byte[] buffer = new byte[fis.available()];    
			fis.read(buffer);    
			fis.close();    
			// 清空response    
			response.reset();    
			// 设置response的Header    
			response.addHeader("Content-Disposition", "attachment;filename="    
					+ new String(filename.getBytes("UTF-8"), "ISO-8859-1"));    
			response.addHeader("Content-Length", "" + file.length());    
			OutputStream toClient = new BufferedOutputStream(    
					response.getOutputStream());    
			response.setContentType("application/vnd.ms-excel;charset=gb2312");    
			toClient.write(buffer);    
			toClient.flush();    
			toClient.close();    
		} catch (IOException ex) {    
			ex.printStackTrace();    
		}    
		
	}

	/**
     * @author zhangpp <br/>
     * @Title: save  <br/>
     * @Description: 新增 <br/>
     * @param dhDepositMoney
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute DhDepositMoney dhDepositMoney) {
    	AbstractSysUser currentUser = getCurrentUser();
    	dhDepositMoney.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	dhDepositMoney.setModifierName(currentUser.getName());
        dhDepositMoneyService.saveUpdateAndDelete(dhDepositMoney, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangpp <br/>
     * @Title: remove  <br/>
     * @Description: 删除<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhDepositMoneyService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangpp <br/>
     * @Title: disable  <br/>
     * @Description: 禁用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhDepositMoneyService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangpp <br/>
     * @Title: enable <br/>
     * @Description: 启用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	dhDepositMoneyService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangpp <br/>
     * @Title: modify  <br/>
     * @Description: 修改 <br/>
     * @param dhDepositMoney
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute DhDepositMoney dhDepositMoney) {
    	AbstractSysUser currentUser = getCurrentUser();
    	dhDepositMoney.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	dhDepositMoney.setModifierName(currentUser.getName());
    	dhDepositMoneyService.saveUpdateAndDelete(dhDepositMoney, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangpp <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询", response = DhDepositMoney.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       DhDepositMoney dhDepositMoney = dhDepositMoneyService.selectById(id);
       if(null == dhDepositMoney) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(dhDepositMoney);
    }
    
    /**
     * @author zhangpp <br/>
     * @Title: list  <br/>
     * @Description: 条件查询 <br/>
     * @param dhDepositMoneyExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询",response = DhDepositMoney.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute DhDepositMoneyExt dhDepositMoneyExt){
        dhDepositMoneyExt.notDeleted();
        PageVo page = getPage(dhDepositMoneyExt);
        int records = dhDepositMoneyService.countByExt(dhDepositMoneyExt);
        page.setRecords(records);
        if (records > 0) {
            List<DhDepositMoney> dhDepositMoneys = dhDepositMoneyService.selectByExt(dhDepositMoneyExt);
            page.setRows(dhDepositMoneys);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
